window.onload = function () {
  function initStudent() {
    //发送ajax请求,获取学员信息
    axios({
      url: "/student/list",
      // `headers` 是即将被发送的自定义请求头,带过去token令牌.
      // headers: { "Authorization": window.localStorage.getItem('my_token8283') },
    }).then((res) => {
      //console.log(res);
      if (res.data.code == 0) {
        //渲染学生数据
        renderData(res.data.data);
      }
    });
  }
  initStudent();

  //我们封装一个函数来渲染学生数据.
  function renderData(arr) {
    document.querySelector("tbody").innerHTML = arr
      .map((item, index) => {
        return `<tr>
                    <th scope="row">${item.id}</th>
                    <td>${item.name}</td>
                    <td>${item.age}</td>
                    <td>${item.sex}</td>
                    <td>${item.group}</td>
                    <td>${item.phone}</td>
                    <td>${item.salary}</td>
                    <td>${item.truesalary}</td>
                    <td>${item.province + item.city + item.county}</td>
                    <td>
                    <button type="button" class="btn btn-primary btn-sm" data-id="${
                      item.id
                    }" data-bs-toggle="modal"
                    data-bs-target="#addModal">修改</button>
                    <button type="button" class="btn btn-danger btn-sm delete" data-id="${
                      item.id
                    }">删除</button>
                    </td>
                </tr>`;
      })
      .join("");
  }

  //获取元素
  let addModal = document.getElementById("addModal"); //模态框
  let provinceSelect = addModal.querySelector('[name="province"]'); //省下拉菜单
  let citySelect = addModal.querySelector('[name="city"]'); //市下拉菜单
  let countySelect = addModal.querySelector('[name="county"]'); //县区下拉菜单
  let studentId = null; //学生id

  //模态框显示事件-只要模态框显示就会触发这个事件
  addModal.addEventListener("show.bs.modal", function (e) {
    //发送ajax请求,获取所有省,并渲染
    axios({
      url: "/geo/province",
    }).then((res) => {
      //console.log(res);
      if (res.status == 200) {
        //渲染省.
        let str = `<option selected value="">--省--</option>`;
        str += res.data
          .map((item) => {
            return `<option value="${item}">${item}</option>`;
          })
          .join("");
        provinceSelect.innerHTML = str;
      }
    });

    //给省下拉菜单设置值改变事件- 获取市
    provinceSelect.addEventListener("change", function () {
      citySelect.innerHTML = `<option selected value="">--市--</option>`;
      countySelect.innerHTML = `<option selected value="">--县--</option>`;
      //判断是否选择的为--省--
      if (provinceSelect.value == "") {
        return;
      }
      //发送ajax请求
      axios({
        url: "/geo/city",
        params: {
          pname: provinceSelect.value,
        },
      }).then((res) => {
        //console.log(res);
        //渲染市.
        let str = `<option selected value="">--市--</option>`;
        str += res.data
          .map((item) => {
            return `<option value="${item}">${item}</option>`;
          })
          .join("");
        citySelect.innerHTML = str;
      });
    });

    //给市下拉菜单设置值改变事件- 获取县
    citySelect.addEventListener("change", function () {
      countySelect.innerHTML = `<option selected value="">--县--</option>`;
      //判断是否选择为--市--
      if (citySelect.value == "") {
        return;
      }
      //发送请求.
      axios({
        url: "/geo/county",
        params: {
          pname: provinceSelect.value,
          cname: citySelect.value,
        },
      }).then((res) => {
        //console.log(res);
        //渲染县.
        let str = `<option selected value="">--县--</option>`;
        str += res.data
          .map((item) => {
            return `<option value="${item}">${item}</option>`;
          })
          .join("");
        countySelect.innerHTML = str;
      });
    });

    //是哪个按钮让模态框显示的
    //console.log('显示了',e.relatedTarget);
    if (e.relatedTarget.innerText == "添加学员") {
      //对市和县设置默认值.
      citySelect.innerHTML = `<option selected value="">--市--</option>`;
      countySelect.innerHTML = `<option selected value="">--县--</option>`;
      //console.log('添加学员');
      document.getElementById("addModalLabel").innerText = "录入新学员";
      addModal.querySelector(".tianjia").style.display = "inline-block";
      addModal.querySelector(".xiugai").style.display = "none";
      addModal.querySelector('[type="reset"]').style.display = "inline-block";
    } else {
      //console.log('修改学员',e.relatedTarget.getAttribute('data-id'));
      document.getElementById("addModalLabel").innerText = "修改学员信息";
      addModal.querySelector(".tianjia").style.display = "none";
      addModal.querySelector(".xiugai").style.display = "inline-block";
      addModal.querySelector('[type="reset"]').style.display = "none";
      //编辑第一大步: 点击修改按钮,获取学生id,发送ajax请求获取该学生的详情,依次的赋值给form表单标签
      studentId = e.relatedTarget.getAttribute("data-id"); //要修改信息的学生id
      console.log("学生id", studentId);
      axios({
        method: "get",
        url: "/student/one",
        params: {
          id: studentId,
        },
      }).then((res) => {
        console.log(res);
        let obj = res.data.data; //取出这个学生的信息对象.
        addModal.querySelector('[name="name"]').value = obj.name; //姓名
        addModal.querySelector('[name="age"]').value = obj.age; //年龄
        addModal.querySelector('[name="group"]').value = obj.group; //组
        if (obj.sex == "男") {
          addModal.querySelectorAll('[name="sex"]')[0].checked = true;
        } else {
          addModal.querySelectorAll('[name="sex"]')[1].checked = true;
        }
        addModal.querySelector('[name="phone"]').value = obj.phone; //手机
        addModal.querySelector('[name="salary"]').value = obj.salary; //期望工资
        addModal.querySelector('[name="truesalary"]').value = obj.truesalary; //实际工资
        //因为一开始我们就会加载省的数据.所以就做匹配就好了
        addModal.querySelector('[name="province"]').value = obj.province; //省
        //因为一开始没有市和县的数据.所以直接赋值.
        addModal.querySelector(
          '[name="city"]'
        ).innerHTML = `<option selected value="${obj.city}">${obj.city}</option>`;
        addModal.querySelector(
          '[name="county"]'
        ).innerHTML = `<option selected value="${obj.county}">${obj.county}</option>`;
      });
    }
  });

  //模态框表单-验证规则
  function student() {
    return {
      fields: {
        name: {
          validators: {
            notEmpty: {
              message: "姓名不能为空",
            },
            stringLength: {
              min: 2,
              max: 10,
              message: "姓名长度2~10位",
            },
          },
        },
        age: {
          validators: {
            notEmpty: {
              message: "年龄不能为空",
            },
            greaterThan: {
              value: 18,
              message: "年龄不能小于18岁",
            },
            lessThan: {
              value: 60,
              message: "年龄不能超过60岁",
            },
          },
        },
        sex: {
          validators: {
            choice: {
              min: 1,
              max: 1,
              message: "请选择性别",
            },
          },
        },
        group: {
          validators: {
            notEmpty: {
              message: "组号不能为空",
            },
            regexp: {
              regexp: /^\d{1,2}$/,
              message: "请选择有效的组号",
            },
          },
        },
        phone: {
          validators: {
            notEmpty: {
              message: "手机号不能为空",
            },
            regexp: {
              regexp: /^1\d{10}$/,
              message: "请填写有效的手机号",
            },
          },
        },
        salary: {
          validators: {
            notEmpty: {
              message: "实际薪资不能为空",
            },
            greaterThan: {
              value: 800,
              message: "期望薪资不能低于800",
            },
            lessThan: {
              value: 100000,
              message: "期望薪资不能高于100000",
            },
          },
        },
        truesalary: {
          validators: {
            notEmpty: {
              message: "实际薪资不能为空",
            },
            greaterThan: {
              value: 800,
              message: "实际薪资不能低于800",
            },
            lessThan: {
              value: 100000,
              message: "实际薪资不能高于100000",
            },
          },
        },
        province: {
          validators: {
            notEmpty: {
              message: "省份必填",
            },
          },
        },
        city: {
          validators: {
            notEmpty: {
              message: "市必填",
            },
          },
        },
        county: {
          validators: {
            notEmpty: {
              message: "县必填",
            },
          },
        },
      },
    };
  }

  //给表单添加验证规则.
  $(".add-form").bootstrapValidator(student());

  //添加学员
  addModal.querySelector(".tianjia").addEventListener("click", function () {
    //调用表单的输入规则验证
    //获取表单对象
    //手动触发验证
    $(".add-form").data("bootstrapValidator").validate();
    if ($(".add-form").data("bootstrapValidator").isValid()) {
      //表单提交的方法、比如ajax提交
      //console.log("添加学生的操作");
      //通过formData对象获取表单元素的值.
      let fd = new FormData(addModal.querySelector("form"));
      //后端接口不支持formData,那就把formData转成普通的对象嘛.
      let data = {};
      fd.forEach((value, key) => {
        console.log(value, key);
        data[key] = value;
      });
      //发送ajax请求,完成学生新增
      axios({
        method: "post",
        url: "/student/add",
        data,
      }).then((res) => {
        if (res.data.code == 0) {
          toastr.success("新增成功!");
          //模态框隐藏.
          $(addModal).modal("hide");
          //重新加载数据
          initStudent();
          //表单重置.
          addModal.querySelector("form").reset(); //数据重置
          $(`form`).data("bootstrapValidator").resetForm(); //验证规则重置
        }
      });
    }
  });

  //修改学员
  addModal.querySelector(".xiugai").addEventListener("click", function () {
    $(".add-form").data("bootstrapValidator").validate();
    if ($(".add-form").data("bootstrapValidator").isValid()) {
      //编辑第二大步.
      //获取修改后的学生信息.
      let fd = new FormData(addModal.querySelector("form"));
      //后端接口不支持formData,那就把formData转成普通的对象嘛.
      let data = { id: studentId };
      fd.forEach((value, key) => {
        console.log(value, key);
        data[key] = value;
      });
      //axios做修改
      axios({
        method: "put",
        url: "/student/update",
        data,
      }).then((res) => {
        if (res.data.code == 0) {
          toastr.success("修改成功!");
          //模态框隐藏.
          $(addModal).modal("hide");
          //重新加载数据
          initStudent();
          //表单重置.
          addModal.querySelector("form").reset(); //数据重置
          $(`form`).data("bootstrapValidator").resetForm(); //验证规则重置
        }
      });
    }
  });

  //表单重置.
  addModal.querySelector(".chongzhi").addEventListener("click", function () {
    //表单重置.
    addModal.querySelector("form").reset(); //数据重置
    $(`form`).data("bootstrapValidator").resetForm(); //验证规则重置
  });

  //给模态框设置隐藏事件.
  addModal.addEventListener("hidden.bs.modal", function () {
    //表单重置.
    addModal.querySelector("form").reset(); //数据重置
    $(`form`).data("bootstrapValidator").resetForm(); //验证规则重置
  });


   // 删除学生. 
   document.querySelector('tbody').addEventListener('click',function(e){
    if(e.target.classList.contains('delete')){
      let id = e.target.getAttribute('data-id');//要删除的学生id
      console.log(id);
      axios({
        method:'delete',
        url:'/student/delete',
        params:{
          id
        }
      }).
      then(res=>{
        if(res.data.code == 0){
          toastr.success('删除成功!');
          initStudent();
        }
      })
    }
  });

};
